package com.web.graduationpro.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.web.graduationpro.dao.service.ArticleService;
import com.web.graduationpro.dao.service.GoodsService;
import com.web.graduationpro.dao.service.InstrumentSchoolService;
import com.web.graduationpro.dao.service.MemberService;
import com.web.graduationpro.dao.service.OrderMiddleService;
import com.web.graduationpro.dao.service.OrderService;
import com.web.graduationpro.dao.service.ShoppingCartMiddleService;
import com.web.graduationpro.dao.service.ShoppingCartService;
import com.web.graduationpro.dao.service.TeacherService;
import com.web.graduationpro.model.Goods;
import com.web.graduationpro.model.Member;
import com.web.graduationpro.model.Order;
import com.web.graduationpro.model.OrderMiddle;
import com.web.graduationpro.model.ShoppingCart;
import com.web.graduationpro.model.ShoppingCartMiddle;

@Controller
@RequestMapping("/buy/*")
public class BuyController {

	@Resource(name="instrumentSchoolServiceImpl")
	private InstrumentSchoolService instrumentSchoolServiceImpl;
	
	@Resource(name="teacherServiceImpl")
	private TeacherService teacherServiceImpl;
	
	@Resource(name="goodsServiceImpl")
	private GoodsService goodsServiceImpl;
	
	@Resource(name="articleServiceImpl")
	private ArticleService articleServiceImpl;
	
	@Resource(name="shoppingCartMiddleServiceImpl")
	private ShoppingCartMiddleService shoppingCartMiddleServiceImpl;
	
	@Resource(name="shoppingCartServiceImpl")
	private ShoppingCartService shoppingCartServiceImpl;
	
	@Resource(name="memberServiceImpl")
	private MemberService memberServiceImpl;
	
	@Resource(name="orderServiceImpl")
	private OrderService orderServiceImpl;
	
	@Resource(name="orderMiddleServiceImpl")
	private OrderMiddleService orderMiddleServiceImpl;
	
	@RequestMapping(value = "/addShopingCart", method = RequestMethod.POST)  
    public void addShopingCart(HttpServletRequest request,HttpServletResponse reponse) {  
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		 String result = "error";
		
		String id = request.getParameter("id");
		String num = request.getParameter("num");
		
		int number = 1;
		if(num!=null && !"".equals(num.trim())){
			number = Integer.parseInt(num);
		}
		
		Member member = null;
		int loginUser = 0;
		if(request.getSession().getAttribute("userid")!=null){
			loginUser = (Integer) request.getSession().getAttribute("userid");
		}
		
		if(loginUser!=0){
			member = (Member) memberServiceImpl.findById(Member.class, loginUser);
		}
		
		if(member!=null){
			if(id!=null && !"".equals(id.trim())){
				Goods goods = (Goods)goodsServiceImpl.findById(Goods.class, Integer.parseInt(id));
				
				Object[] cses = new Object[1];
				cses[0] = member.getId();
				String hql = " From ShoppingCart sc where sc.user.id=?";
				List<ShoppingCart> shoppingCarts = shoppingCartServiceImpl.findByPage(hql,cses,0,1);
				ShoppingCart sc = null;
				if(shoppingCarts!=null && shoppingCarts.size()!=0){
					sc = shoppingCarts.get(0);
				}else{
					sc = new ShoppingCart();
					
					sc.setUser(member);
					shoppingCartServiceImpl.save(sc);
				}
				
				if(sc!=null){
					Object[] csesc = new Object[1];
					csesc[0] = Integer.parseInt(id);
					String hqlc = " From ShoppingCartMiddle scm where scm.goods.id=?";
					List<ShoppingCartMiddle> scms = shoppingCartMiddleServiceImpl.findByPage(hqlc,csesc,0,1);
					
					ShoppingCartMiddle scm = null;
					if(scms!=null && scms.size()!=0){
						scm = scms.get(0);
						scm.setNumber(scm.getNumber()+number);
						shoppingCartMiddleServiceImpl.updata(scm);
					}else{
						scm = new ShoppingCartMiddle();
						
						scm.setGoods(goods);
						scm.setNumber(number);
						scm.setShoppingCart(sc);
						shoppingCartMiddleServiceImpl.save(scm);
					}
					result = "success";
				}
			}
		}else{
			result = "logout";
		}
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }  
	
	@RequestMapping(value = "/toShoppingcart", method = RequestMethod.GET)  
    public String toShoppingcart(HttpServletRequest request,HttpServletResponse reponse) {  
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		String id = request.getParameter("id");

		Member member = null;
		int loginUser = 0;
		if(request.getSession().getAttribute("userid")!=null){
		   loginUser = (Integer) request.getSession().getAttribute("userid");
		}
		if(loginUser!=0){
			member = (Member) memberServiceImpl.findById(Member.class, loginUser);
		}
		
		if(member!=null){
			if(id!=null && !"".equals(id.trim())){
				shoppingCartMiddleServiceImpl.deleteById(ShoppingCartMiddle.class, Integer.parseInt(id));
			}
			List<ShoppingCartMiddle> scms = null;
			Object[] cses = new Object[1];
			cses[0] = member.getId();
			String hql = " From ShoppingCart sc where sc.user.id=?";
			List<ShoppingCart> shoppingCarts = shoppingCartServiceImpl.findByPage(hql,cses,0,1);
			ShoppingCart sc = null;
			if(shoppingCarts!=null && shoppingCarts.size()!=0){
				sc = shoppingCarts.get(0);
			}else{
				sc = new ShoppingCart();
				
				sc.setUser(member);
				shoppingCartServiceImpl.save(sc);
			}
			
			if(sc!=null){
				Object[] csesc = new Object[1];
				csesc[0] = sc.getId();
				String hqlc = " From ShoppingCartMiddle scm where scm.shoppingCart.id=?";
				scms = shoppingCartMiddleServiceImpl.findByPage(hqlc,csesc,0,0);
			    request.setAttribute("scms", scms);
			}
			return "/shoppingcart";
		}else{
			return "/login";
		}
    }  
	
	@RequestMapping(value = "/suborder", method = RequestMethod.GET)  
    public String suborder(HttpServletRequest request,HttpServletResponse reponse) {  
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		Member member = null;
		int loginUser = 0;
		if(request.getSession().getAttribute("userid")!=null){
		   loginUser = (Integer) request.getSession().getAttribute("userid");
		}
		if(loginUser!=0){
			member = (Member) memberServiceImpl.findById(Member.class, loginUser);
		}
		
		if(member!=null){
			List<ShoppingCartMiddle> scms = null;
			Object[] cses = new Object[1];
			cses[0] = member.getId();
			String hql = " From ShoppingCart sc where sc.user.id=?";
			List<ShoppingCart> shoppingCarts = shoppingCartServiceImpl.findByPage(hql,cses,0,1);

			if(shoppingCarts!=null && shoppingCarts.size()!=0){
				ShoppingCart sc = shoppingCarts.get(0);
				Object[] csesc = new Object[1];
				csesc[0] = sc.getId();
				String hqlc = " From ShoppingCartMiddle scm where scm.shoppingCart.id=?";
				scms = shoppingCartMiddleServiceImpl.findByPage(hqlc,csesc,0,0);
			    request.setAttribute("scms", scms);
			}
			return "/suborder";
		}else{
			return "/login";
		}
    }  
	
	@RequestMapping(value = "/addorder", method = RequestMethod.POST)  
    public String addorder(HttpServletRequest request,HttpServletResponse reponse) {  
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		Order order = new Order();
		
		//订单号
		Date nowDate = new Date();
		DateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");   
		String orderNum = format1.format(nowDate);  
		order.setOrderNum(orderNum);

		//真实姓名
		String trueName = request.getParameter("trueName");
		if(trueName!=null && !"".equals(trueName.trim())){
			order.setTrueName(trueName);
		}
		
		//收货地址
		String shippingAddress = request.getParameter("shippingAddress");
		if(shippingAddress!=null && !"".equals(shippingAddress.trim())){
			order.setShippingAddress(shippingAddress);
		} 
		
		//联系方式
		String information = request.getParameter("information");
		if(information!=null && !"".equals(information.trim())){
			order.setInformation(information);
		}    
		
		//邮编
		String postcode = request.getParameter("postcode");
		if(postcode!=null && !"".equals(postcode.trim())){
			order.setPostcode(postcode);
		}        
		
		//收货方式
		String receivingWay = request.getParameter("receivingWay");
		if(receivingWay!=null && !"".equals(receivingWay.trim())){
			order.setShippingway(receivingWay);
		}            
		
		//订单状态
		order.setOrderState("处理中");  
		
		//订单总价
		String totalprice1 = request.getParameter("totalprice1");
		String totalprice2 = request.getParameter("totalprice2");
		double totalPrice = 0;
		if("快递送货".equals(receivingWay.trim())){
			totalPrice = Double.valueOf(totalprice2);
		}else{
			totalPrice = Double.valueOf(totalprice1);
		}
		order.setTotalPrice(totalPrice);
		
		 //创建时间
		DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
		String createTime = format2.format(nowDate);  
		order.setCreateTime(createTime);     
		
		Member member = null;
		int loginUser = 0;
		if(request.getSession().getAttribute("userid")!=null){
		   loginUser = (Integer) request.getSession().getAttribute("userid");
		}
		if(loginUser!=0){
			member = (Member) memberServiceImpl.findById(Member.class, loginUser);
		}
		
		if(member!=null){
			order.setMember(member);
			orderServiceImpl.save(order);

			List<ShoppingCartMiddle> scms = null;
			Object[] cses = new Object[1];
			cses[0] = member.getId();
			String hql = " From ShoppingCart sc where sc.user.id=?";
			List<ShoppingCart> shoppingCarts = shoppingCartServiceImpl.findByPage(hql,cses,0,1);

			if(shoppingCarts!=null && shoppingCarts.size()!=0){
				ShoppingCart sc = shoppingCarts.get(0);
				Object[] csesc = new Object[1];
				csesc[0] = sc.getId();
				String hqlc = " From ShoppingCartMiddle scm where scm.shoppingCart.id=?";
				scms = shoppingCartMiddleServiceImpl.findByPage(hqlc,csesc,0,0);
				
				if(scms!=null && scms.size()!=0){
					boolean b = false;
					for(int i=0;i<scms.size();i++){
						b = false;
						ShoppingCartMiddle scm = scms.get(i);
						OrderMiddle om = new OrderMiddle();
						om.setGoods(scm.getGoods());
						om.setNumber(scm.getNumber());
						om.setOrder(order);
						
						orderMiddleServiceImpl.save(om);
						shoppingCartMiddleServiceImpl.delete(scm);
						b = true;
					}
					if(!b){
						orderServiceImpl.delete(order);
					}
				}
			}
			return "/user/info";
		}else{
			return "/login";
		}
    }  
}
